import $ from "jquery"


function sendMessageToContentScript(message, callback) {
  chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
    chrome.tabs.sendMessage(tabs[0].id, message, function (response) {
      callback && callback(response);
    });
  });
}

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if(request.cmd === 'xhr') {
    sendResponse('')
    $.get('http://hs.taokezhushou.com/v1/plan/get?goods_id=' + request.item_url, r => {
      console.log(r)
      if (r.status === 'SUCCESS') {
        sendMessageToContentScript({
          cmd: 'xhr',
          index: request.index,
          value: r.data.commission_rate / 100
        })
      } else {
        sendMessageToContentScript({
          cmd: 'xhr',
          index: request.index,
          value: null
        })
      }
    })
  }
});

chrome.tabs.onUpdated.addListener(function (id, info, tab) {
  if (info.status === 'complete' && tab.url.includes('https://pub.alimama.com/manage/cpevent/audit.htm')) {
    sendMessageToContentScript({
      cmd: 'init'
    })
  }
})
